package com.bstek.uflo.form.command;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;

import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.uflo.command.Command;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.form.model.TableColumn;
import com.bstek.uflo.form.model.TableDefinition;
import com.bstek.uflo.utils.EnvironmentUtils;
import com.bstek.uflo.utils.IDGenerator;

/**
 * @author Jacky.gao
 * @since 2013年11月8日
 */
public class SaveTableCommand implements Command<TableDefinition> {
	private Collection<TableDefinition> tables;

	public SaveTableCommand(Collection<TableDefinition> tables) {
		this.tables = tables;
	}

	public TableDefinition execute(Context context) {
		Session session = context.getSession();
		saveTables(session,tables);
		return null;
	}
	
	private void saveTables(Session session,Collection<TableDefinition> tableDefs){
		for (TableDefinition table : tableDefs) {
			EntityState state = EntityUtils.getState(table);
			if (state.equals(EntityState.NEW)) {
				table.setId(IDGenerator.getInstance().nextId());
				table.setCreateDate(new Date());
				table.setCategoryId(EnvironmentUtils.getEnvironment().getCategoryId());
				session.save(table);
			} else if (state.equals(EntityState.MODIFIED)) {
				session.saveOrUpdate(table);
			} else if (state.equals(EntityState.DELETED)) {
				session.createQuery(
						"delete " + TableColumn.class.getName() + " where tableId=:tableId")
						.setLong("tableId", table.getId()).executeUpdate();
				session.delete(table);
			}
			List<TableColumn> columns=table.getColumns();
			if(columns!=null && columns.size()>0){
				saveTableColumns(columns,session);
			}
			List<TableDefinition> children=table.getSlaveTables();
			if(children!=null && children.size()>0){
				saveTables(session,children);
			}
		}
	}
	
	private void saveTableColumns(List<TableColumn> columns,Session session){
		for (TableColumn column : columns) {
			EntityState state = EntityUtils.getState(column);
			if (state.equals(EntityState.NEW)) {
				column.setId(IDGenerator.getInstance().nextId());
				session.save(column);
			} else if (state.equals(EntityState.MODIFIED)) {
				session.saveOrUpdate(column);
			} else if (state.equals(EntityState.DELETED)) {
				session.delete(column);
			}
		}
	}
}
